package com.lily.aidouzixun.ui;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.util.Validator;

import java.lang.ref.WeakReference;
import java.util.Locale;

/**
 * 自定义的WebView
 */
public class MyWebView extends WebView {
	private static String TAG = "MyWebView";
	private static MyHandler myHandler;
	private Context mContext;
	private Activity mActivity;
	private ProgressBar pBar;	//进度条
	long last_time = 0;


	public MyWebView(Context context) {
		super(context);
		init(context);
		setListeners();
	}

	public MyWebView(Context context,AttributeSet attrs){
		super(context,attrs);
		init(context);
		setListeners();
	}
	
	/**
	 * 初始化操作
	 */
	public  void init(Context  context) {
		// TODO Auto-generated method stub
		this.mContext = context;
		myHandler = new MyHandler(this);
		//获得焦点
		requestFocus();
		//设置参数
		WebSettings webSettings = getSettings();
		webSettings.setDefaultTextEncodingName("utf-8");	//编码
		webSettings.setJavaScriptEnabled(true);		//	设置支持js
		webSettings.setSupportZoom(false);	//不支持缩放
		webSettings.setBuiltInZoomControls(false);	//显示缩放按钮
		webSettings.setGeolocationEnabled(true);	//启用地理定位
		webSettings.setGeolocationDatabasePath(context.getFilesDir().getPath());	//设置定位的数据库路径
		//设置自己的Client
		setWebViewClient(new MyWebViewClient(context));
		setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		setHorizontalScrollBarEnabled(true);	//设置水平和垂直的滚动条隐藏
		setVerticalScrollBarEnabled(true);
		webSettings.setUseWideViewPort(true);	//可按照任意比例缩放
		webSettings.setLoadWithOverviewMode(true); //该方法能将网页缩小后全部显示
		float scale = getScale();
		setInitialScale((int)(100 / scale));
		
		int screenDensity = getResources().getDisplayMetrics().densityDpi ;   
		WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM ;   
		switch (screenDensity){   
		case DisplayMetrics.DENSITY_LOW :  
		    zoomDensity = WebSettings.ZoomDensity.CLOSE;  
		    break;  
		case DisplayMetrics.DENSITY_MEDIUM:  
		    zoomDensity = WebSettings.ZoomDensity.MEDIUM;  
		    break;  
		case DisplayMetrics.DENSITY_HIGH:  
		    zoomDensity = WebSettings.ZoomDensity.FAR;  
		    break ;  
		}  
		webSettings.setDefaultZoom(zoomDensity);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				long current_time = System.currentTimeMillis();
				long d_time = current_time - last_time;
				if (d_time < 300) {	//如果两次点击间隙小于0.3s,不让webview响应
					last_time = current_time;
					return true;
				} else {
					last_time = current_time;
				}
				break;
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 设置监听
	 */
	private void setListeners() {
		//设置下载的监听
		setDownloadListener(new DownloadListener() {
			@Override
			public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
				try {
					startBrowser(url);
					finishActivity();
					T.shortToast(mContext, "启动第三方浏览器进行下载，请稍等！");
				} catch (Exception e) {
					L.e(TAG, "onDownloadStart--error!");
				}
			}
		});
		//设置WebChromeClient
		setWebChromeClient(new WebChromeClient(){
			@Override
			public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
				try {
					if (mActivity.isFinishing()) {
						result.cancel();
						return true;
					}

					AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
					builder.setTitle("提示对话框");
					builder.setMessage(message);
					builder.setPositiveButton(android.R.string.ok,
							new AlertDialog.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									result.confirm();
								}
							});
					builder.setCancelable(false);
					builder.create();
					builder.show();
				}
				catch (Exception e) {
					e.printStackTrace();
					result.cancel();
				}
				return true;
			}

			/**
			 * 获取地理位置权限
			 * @param origin
			 * @param callback
			 */
			@Override
			public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
				try {
					AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
					builder.setMessage("网站 '" + origin + "' 请求获取您的位置信息");
					AlertDialog.OnClickListener dialogButtonOnClickListener = new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int clickedButton) {
							if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
								callback.invoke(origin, false, false);
							} else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
								callback.invoke(origin, true, true);
							}
						}
					};
					builder.setPositiveButton("拒绝", dialogButtonOnClickListener);
					builder.setNegativeButton("同意", dialogButtonOnClickListener);
					builder.setCancelable(false);
					builder.show();
					super.onGeolocationPermissionsShowPrompt(origin, callback);
					L.e(TAG, "onGeolocationPermissionsShowPrompt:" + origin);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			/**
			 * 改变进度条
			 * @param view
			 * @param newProgress
			 */
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if(pBar != null) {
					if (newProgress == 100) {
						pBar.setVisibility(View.GONE);
					} else {
						pBar.setVisibility(View.VISIBLE);
						pBar.setProgress(newProgress);
					}
				}
				super.onProgressChanged(view, newProgress);
			}
		});

	}

	/**
	 * 设置进度条
	 */
	public void setProgressBar(ProgressBar progressBar) {
		this.pBar = progressBar;
	}
	/**
	 * 开启浏览器
	 * @param url
	 */
	private void startBrowser(String url) {
		if (!Validator.isEffective(url)) {
			return;
		}
		try {
			Uri uri = Uri.parse(url);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
		} catch (Exception e) {
			L.e(TAG, "startBrowser error!");
		}
	}

	/**
	 * 设置WebView的Activity
	 * @param activity
	 */
	public void setActivity(Activity activity) {
		this.mActivity = mActivity;
	}

	/**
	 * 开启一个Activity
	 * @param intent
	 */
	private void startActivity(Intent intent) {
		if (this.mContext != null) {
			this.mContext.startActivity(intent);
		}
	}

	/**
	 * 设置Context对象
	 */
	public void setContext(Context context) {
		this.mContext = context;
	}

	/**
	 * 关闭Activity
	 */
	private void finishActivity() {
		if (this.mActivity != null) {
			this.mActivity.finish();
		}
	}

	/**
	 * 自定义的WebViewClient
	 *
	 */
	public static class MyWebViewClient extends WebViewClient{
		private Context context;
		
		public MyWebViewClient(Context context){
			this.context = context;
		}

		/**
		 * 请求完成时回调的方法
		 * @param view
		 * @param url
		 */
		@Override
		public void onPageFinished(WebView view, String url) {
			Log.v(TAG, "onPageFinished-->"+url);
			super.onPageFinished(view, url);
		}

		/**
		 * 请求开始时回调的方法
		 * @param view
		 * @param url
		 * @param favicon
		 */
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onPageStarted-->"+url);
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onReceivedError-->"+failingUrl);
			super.onReceivedError(view, errorCode, description, failingUrl);
		}
		
		/**
		 * 对网页超链接的监听
		 *  当Api小于11时，并不是每次都会调用
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// TODO Auto-generated method stub
			L.v(TAG, "shouldOverrideUrlLoading-->"+url);
			//得到网页的前缀
			String ref = url.substring(0,url.indexOf(":"));
			//针对ref做协议判断
			if(ref.equals("tel")){	//拨打电话的超链接
				L.v(TAG, "拨打电话，电话号码为："+Uri.parse(url.toLowerCase(Locale.ENGLISH)));
				Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse(url.toLowerCase(Locale.ENGLISH)));
				context.startActivity(intent);
				return true;
			}
			view.loadUrl(url);
			return true;
		}
		/**
		 * 拦截非超链接请求
		 */
		@Override
		public void onLoadResource(WebView view, String url) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onLoadResource-->"+url);
			super.onLoadResource(view, url);
		}
	}

	/**
	 * 加载url
	 */
	public void startLoadUrl(final String url, final String postData) {
		if (Validator.isEffective(url)) {
			post(new Runnable() {
				@Override
				public void run() {
					try {
						if (Validator.isEffective(postData)) {	//如果有请求数据
							postUrl(url, postData.getBytes());
						} else {
							if (url.contains("://")) {
								loadUrl(url);
							} else {
								loadUrl("http://" + url);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

	/**
	 * 通过回调js方法，把客户端中的urid传到html中
	 */
	public void cbUrid(String jsMethod) {
		String urid = MyConfig.getUserId(mContext);
		String url = "javascript:" + jsMethod + "(‘"+ urid + "’)";
		loadUrl(url);
	}

	/**
	 * 得到我的Handler
	 * @return
     */
	public static MyHandler getMyHandler() {
		return myHandler;
	}

	/**
	 * 自定义的Handler
	 */
	static class MyHandler extends Handler {
		WeakReference<MyWebView> mWebViewReference;

		/**
		 * 构造方法，传递mWebView对象，防止内存泄露
		 * @param mWebView
		 */
		MyHandler(MyWebView mWebView) {
			mWebViewReference = new WeakReference<MyWebView>(mWebView);
		}

		@Override
		public void handleMessage(Message msg) {
			try {
				final MyWebView myWebView = (MyWebView) mWebViewReference.get();
				if(myWebView !=  null) {
					super.handleMessage(msg);
					switch (msg.what) {
						case MessageType.SHOW_DIALOG:
							break;
						case MessageType.CLOSE_DIALOG:
							break;
						case MessageType.PULL_REFRESH:	//下拉刷新
							myWebView.reload();
							break;
						case MessageType.PUSH_MOREDATA:	//上拉加载更多

							break;
						default:
							break;
					}
				}
			} catch (Exception e) {
				L.e(TAG, "handleMessage Exception!");
			}
		}
	}
}
